package export

import (
	"context"
	"github.com/google/uuid"
	"github.com/xuri/excelize/v2"
	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"net/http"
	"os"
	"time"
)

type ApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ApiLogic {
	hostname, _ := os.Hostname()
	return &ApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ApiLogic) TestApi(w http.ResponseWriter) (resp *types.ExportResponse, err error) {
	// 1. 准备数据 (这里用模拟数据，实际应从数据库获取)
	data := [][]interface{}{
		{"ID", "姓名", "年龄", "创建时间"},
		{1, "张三", 25, time.Now().Format("2006-01-02 15:04:05")},
		{2, "李四", 30, time.Now().Format("2006-01-02 15:04:05")},
		{3, "王五", 28, time.Now().Format("2006-01-02 15:04:05")},
	}

	// 2. 创建Excel文件
	f := excelize.NewFile()
	defer f.Close()

	// 3. 创建工作表
	index, err := f.NewSheet("Sheet1")
	if err != nil {
		l.Logger.Errorf("创建Sheet失败: %v", err)
		return nil, err
	}

	// 4. 填充数据
	for rowIndex, row := range data {
		for colIndex, value := range row {
			cell, _ := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1)
			f.SetCellValue("Sheet1", cell, value)
		}
	}

	// 5. 设置活动工作表
	f.SetActiveSheet(index)

	// 6. 设置HTTP响应头
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Disposition", "attachment; filename=export.xlsx")
	w.Header().Set("Content-Transfer-Encoding", "binary")

	// 7. 写入Excel文件到响应
	if err := f.Write(w); err != nil {
		l.Logger.Errorf("写入Excel文件失败: %v", err)
		return nil, err
	}

	// 返回nil表示直接处理了响应，不需要框架再处理
	return nil, nil
}
